/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.kits;

import app.dtos.SmsMask;
import app.models.sys.SmsCategory;
import app.models.sys.SmsRecord;
import com.github.sog.config.JFinalApp;
import com.github.sog.config.StringPool;
import com.github.sog.kit.lang.ExceptionKit;
import com.google.common.collect.Maps;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ws.MessageSvc;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-05-20 22:04
 * @since JDK 1.6
 */
public class SmsWsKit {

    public static final String UPDATE_RESPONSE_TEMPLATE = "updateResponseTemplate";
    private static final MessageSvc SMS_SERVICE;
    private static final String SMS_API_USERNAME = "中南城购物中心";
    private static final String SMS_API_PWD      = "123";
    private static final Logger logger           = LoggerFactory.getLogger(SmsWsKit.class);

    static {
        MessageSvc svc;
        try {
            svc = new MessageSvc();
        } catch (Exception e) {
            logger.error("init sms web service is error!", e);
            svc = null;
        }
        SMS_SERVICE = svc;
    }

    /**
     * 发送会员注册信息
     *
     * @param phone  会员手机
     * @param catcha 验证码
     * @param time   有效时间，单位秒
     * @return 是否成功
     */
    public static boolean membreApplySend(String phone, String catcha, int time) {
        final String param = "{\"captcha\": \"" + catcha + "\", \"time\": \"" + time + "\"}";
        SmsCategory smsCategory = SmsCategory.dao.findByMask(SmsMask.MEMBER_APPLY);
        if (smsCategory == null) {
            SmsRecord.dao.recore(phone, catcha, time, "请维护会员注册短信模版");
            logger.error("请维护会员注册短信模版");
        } else {
            String content = StringPool.EMPTY;
            String result = StringPool.EMPTY;
            try {
                Map<String, Object> parmas = Maps.newHashMap();
                parmas.put("captcha", catcha);
                parmas.put("time", time);
                content = renderResponse(smsCategory.getStr("template"), parmas);
                result = SMS_SERVICE.getMessageSvcSoap().sendMessage(SMS_API_USERNAME, SMS_API_PWD, contentSuffix(content), phone);
            } catch (Exception e) {
                SmsRecord.dao.recordAndResultWithException(phone, content, result, ExceptionKit.getStackTraceAsString(e), param);
                return false;
            }
            SmsRecord.dao.recordAndResult(phone, content, result, param);
        }
        return true;
    }

    private static String contentSuffix(String content) {
        return content + JFinalApp.configuration.getProperty("app.sms.suffix", "【中南城购物中心】");
    }

    protected static String renderResponse(String stringTemplate, Map ctx) {
        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate(UPDATE_RESPONSE_TEMPLATE, stringTemplate);
        cfg.setTemplateLoader(stringLoader);
        Writer out = new StringWriter(2048);

        try {
            Template tpl = cfg.getTemplate(UPDATE_RESPONSE_TEMPLATE, StringPool.UTF_8);
            tpl.process(ctx, out);
        } catch (IOException e) {
            logger.error("Get update response template occurs error.", e);
        } catch (TemplateException e) {
            logger.error("Process template occurs error.template content is:\n {}", e, stringTemplate);
            throw new IllegalArgumentException("Error update response template.", e);
        }

        return out.toString();
    }

    public static boolean membreDiningSend(String phone, String voucher, String brandName) {
        final String param = "{\"voucher\": \"" + voucher + "\", \"brandName\": \"" + brandName + "\"}";
        SmsCategory smsCategory = SmsCategory.dao.findByMask(SmsMask.MEMBER_APPLY);
        if (smsCategory == null) {
            SmsRecord.dao.recore(phone, voucher, 0, "请维护餐饮预定短信模版");
            logger.error("请维护餐饮预定短信模版");
        } else {
            String content = StringPool.EMPTY;
            String result = StringPool.EMPTY;
            try {
                Map<String, Object> parmas = Maps.newHashMap();
                parmas.put("voucher", voucher);
                parmas.put("brandName", brandName);
                content = renderResponse(smsCategory.getStr("template"), parmas);
                result = SMS_SERVICE.getMessageSvcSoap().sendMessage(SMS_API_USERNAME, SMS_API_PWD, contentSuffix(content), phone);
            } catch (Exception e) {
                SmsRecord.dao.recordAndResultWithException(phone, content, result, ExceptionKit.getStackTraceAsString(e), param);
                return false;
            }
            SmsRecord.dao.recordAndResult(phone, content, result, param);
        }
        return true;
    }

    public static boolean membreKtvSend(String phone, String captcha) {
        final String param = "{\"captcha\": \"" + captcha + "\"}";
        SmsCategory smsCategory = SmsCategory.dao.findByMask(SmsMask.MEMBER_KTV);
        if (smsCategory == null) {
            SmsRecord.dao.recore(phone, captcha, 0, "请维护KTV预定短信模版");
            logger.error("请维护KTV预定短信模版");
        } else {
            String content = StringPool.EMPTY;
            String result = StringPool.EMPTY;
            try {
                Map<String, Object> parmas = Maps.newHashMap();
                parmas.put("captcha", captcha);
                content = renderResponse(smsCategory.getStr("template"), parmas);
                result = SMS_SERVICE.getMessageSvcSoap().sendMessage(SMS_API_USERNAME, SMS_API_PWD, contentSuffix(content), phone);
            } catch (Exception e) {
                SmsRecord.dao.recordAndResultWithException(phone, content, result, ExceptionKit.getStackTraceAsString(e), param);
                return false;
            }
            SmsRecord.dao.recordAndResult(phone, content, result, param);
        }
        return true;
    }
}
